#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import web
import json
import traceback

from sqlalchemy.orm.exc import NoResultFound
from Umpweb.base import render_jinja
from Umpweb.db import api as db_api
from Umpweb.common import utils
from Umpweb.common.utils import login_required

from Umpweb.base import session, _, render_jinja

render = render_jinja('static/templates/snapshot', encoding='utf-8',)

class Snapshot:
    @login_required
    def GET(self):
        web.header("Content-Type", "text/plain")
        volumes = db_api.volume_get_all()
        volumes_show = []
        for volume in volumes:
            if volume.provisioning == 'thick':
                volume.provisioning_show = '非精简'
            else:
                volume.provisioning_show = '精简'
            if db_api.check_is_adminstrator(session.user.name):
                volumes_show.append(volume)
            else:
                if volume.username == session.user.name:
                    volumes_show.append(volume)
        
        return render.snapshot(volumes=volumes_show)

class SnapshotList:
    def GET(self):
        web.header("Content-Type", "text/plain")
        return render.snapshot_list()

class SnapshotCreate:
    @login_required
    def GET(self):
        x = web.input()
        volume_id = x.get('id')
        volume = db_api.volume_get(volume_id)
        volume.pool = db_api.pool_get(volume.pool_id)
        return render.snapshot_create(volume=volume)

    def POST(self):
        web.header("Content-Type", "application/json")
        values = dict(**web.input())
        body = {"SnapshotCreate":{'params':values}}
        return utils.web_return(body)

class SnapshotDelete:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        body = {"SnapshotDelete":{'params':{'id':x.get('id').strip()}}}
        return utils.web_return(body)
        
class SnapshotUpdate:

    @login_required
    def GET(self):
        x = web.input()
        snapshot = db_api.snapshot_get(x.get('id'))
        return render.snapshot_update(snapshot=snapshot)

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = {
            'id': x.get('id').strip(),
            'name':x.name.strip(),
           }

        body = {"SnapshotUpdate": {'params': values}}
        return utils.web_return(body)


class SnapshotRollback:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = {
            'id': x.get('id').strip(),
           }

        body = {"SnapshotRollback": {'params': values}}
        return utils.web_return(body)

class SnapshotClone:

    @login_required
    def GET(self):
        x = web.input()
        snapshot = db_api.snapshot_get(x.get('id'))
        pools = db_api.pool_get_with_user(web.config._session.user.id)
        volume = db_api.volume_get(snapshot.volume_id)
        pool = db_api.pool_get(volume.pool_id)
        snapshotpath = "%s/%s@%s" % (pool.name, volume.name, snapshot.name)
        return render.snapshot_clone(snapshot=snapshot, pools=pools, 
                pool=pool, snapshotpath=snapshotpath)

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        pool_id = x['pool_id']
        snapshot_id = x['id']
        volume_name = x['tgt_volume']
        name = x['snapshotpath']
        pool = db_api.pool_get(pool_id)
        name2 = "%s/%s" % (pool.name, volume_name)
        
        values = {'name':name, 'name2':name2, 'protocol':pool.protocol}
        body = {"SnapshotClone": {'params': values}}
        return utils.web_return(body)


class GridSnapshot:

    def POST(self):
        web_input = web.input()
        snapshot_id = web_input.get('id')
        filters = {}
        if snapshot_id:
            filters = {'id':snapshot_id}
    
        page, total, records, rows = \
                utils.grid_rows_query(db_api.snapshot_table, web_input, filters=filters)

        for snapshot in rows:
            volume = db_api.volume_get(snapshot.volume_id)
            if volume:
                snapshot.username = volume.username
                snapshot.volumeName = volume.path

        cells = ['id', 'path', 'description', 'volumeName', 'username', 'created_at']

        rows_json = utils.grid_json(
                page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json


class GetSnapshots:

    def GET(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        snapshots = db_api.snapshot_get_with_volume(x.volume_id)
        snapshots = [snapshot.__dict__ for snapshot in snapshots]
        return json.dumps(snapshots)


class GridSnapshotPolicy:

    def POST(self):
        web_input = web.input()
        filters = {}
        page, total, records, rows = \
                utils.grid_rows_query(db_api.snapshot_policy_table, web_input, filters=filters)

        for row in rows:
            
            row.count_show = unit = ''
            if row.unit == 'hours':
                unit = '小时'
            if row.unit == 'days':
                unit = '天'
            if unit:
                row.count_show = "%s %s" % (row.count, unit)


        cells = ['id', 'name', 'count_show', 'unit','username','created_at','operation']

        rows_json = utils.grid_json(
                page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json


class SnapshotPolicyList:

    def GET(self):
        return render.snapshot_policy_list()


class SnapshotTask:

    def GET(self):
        x = web.input()
        volume_id = x.get('volume_id')
        volume = db_api.volume_get(volume_id)
        count = unit = ''
        if volume.snapshot_time:
            count_unit = volume.snapshot_time.split('-')[0]
            count = count_unit[:-1]
            unit = count_unit[-1]
        volume.snapshot_cycle = None
        if unit == 'd' :
            volume.snapshot_cycle = "%s天" % count
        if unit == 'm' :
            volume.snapshot_cycle = "%s分钟" % count
        if unit == 'h' :
            volume.snapshot_cycle = "%s小时" % count
        return render.snapshot_task(volume=volume)

    def POST(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        values = {
            'count':x.count.strip(),
            'unit': x.get('unit').strip(),
            'volume_id':x.volume_id,
           }

        body = {"SnapshotTask": {'params': values}}
        return utils.web_return(body)


class SnapshotPolicyCreate:

    def GET(self):
        return render.snapshot_policy_create()

    def POST(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        values = {
            'count':x.count.strip(),
            'unit': x.get('unit').strip(),
            'name':x.get('name')
           }

        body = {"SnapshotPolicyCreate": {'params': values}}
        return utils.web_return(body)


class SnapshotPolicyDelete:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        body = {"SnapshotPolicyDelete":{'params':{'id':x.get('id').strip()}}}
        return utils.web_return(body)


class SnapshotConsistency:
    def GET(self):
        return render.snapshot_consistency()
